import { assetManager, Prefab, instantiate, Node, log } from 'cc';
import { ResourceManager } from './ResourceManager';
import { PopupConfig, GlobalManager } from '../global/GlobalManager';
import { BundleManager } from './BundleManager';

export class PopupManager {
    private static _instance: PopupManager;
    public static get instance(): PopupManager {
        if (!this._instance) this._instance = new PopupManager();
        return this._instance;
    }

    private prefabCache: Map<string, Prefab> = new Map();
    private bundleCache: Map<string, any> = new Map(); // 缓存bundle引用
    private popups: Map<string, Node> = new Map();

    /**
     * 预加载弹窗 Prefab，支持远程 bundle（serverUrl）
     */
    public async preloadPopup(config: PopupConfig) {
        let prefab: Prefab | null = null;
        console.log(config)
        if ( config.bundle) {
            const bundle = await this.getOrLoadBundle(config);
            prefab = await new Promise<Prefab>((resolve, reject) => {
                console.log('preloadPopup',bundle, config.bundle, config.path);
                bundle.load(config.path, Prefab, (err, p) => {
                    if (err) {
                        reject(err)
                    }else{
                        resolve(p)
                    };
                    
                });
            });
        }else{
            prefab = await new Promise<Prefab>((resolve) => {
                ResourceManager.instance.loadPrefab({name: config.path, bundle: config.bundle, remote: config.isRemote}, (prefab) => {
                    resolve(prefab);
                });
            });
        }
        if (prefab) this.prefabCache.set(config.path, prefab);
        return prefab;
    }

    /**
     * 显示弹窗（优先用缓存），支持远程 bundle（serverUrl）
     */
    public async showPopup(config: PopupConfig, parent?: Node) {
        let prefab = this.prefabCache.get(config.path);
        if (!prefab) {
            await this.preloadPopup(config);
            prefab = this.prefabCache.get(config.path);
        }
        if (!prefab) return null;
        const node = instantiate(prefab);
        if (parent) parent.addChild(node);
        // 传参
        if (config.data && node.getComponent) {
            const comp = node.getComponent(node.name);
            if (comp) Object.assign(comp, config.data);
        }
        this.popups.set(config.path, node);
        return node;
    }

    /**
     * 关闭弹窗
     */
    public closePopup(config: PopupConfig) {
        const node = this.popups.get(config.path);
        if (node) {
            node.destroy();
            this.popups.delete(config.path);
        }
    }

    /**
     * 获取或加载bundle，支持缓存
     */
    private async getOrLoadBundle(config: PopupConfig): Promise<any> {
        // 检查是否应该使用远程加载
        const shouldUseRemote = GlobalManager.shouldUseRemote(config.isRemote || false, true);
    
        const bundleKey = shouldUseRemote ?
            GlobalManager.getRemoteCacheKey(config.bundle!, true) :
            config.bundle!;
    
        // 检查缓存
        if (this.bundleCache.has(bundleKey)) {
            return this.bundleCache.get(bundleKey);
        }
    
        let bundle;
        if (shouldUseRemote) {
            // 远程bundle需要加版本号目录
            const bundleUrl = GlobalManager.getRemoteBundleUrl(config.bundle!);
            console.log(`[PopupManager] 加载远程bundle: ${bundleUrl}`);
            bundle = await BundleManager.instance.loadBundle(bundleUrl);
        } else if (!config.bundle || config.bundle === 'resources') {
            // 资源在 resources bundle
            bundle = "resources";
        } else {
            // 本地其它 bundle
            console.log(`[PopupManager] 加载本地bundle: ${config.bundle}`);
            bundle = await BundleManager.instance.loadBundle(config.bundle!);
        }
    
        this.bundleCache.set(bundleKey, bundle);
        return bundle;
    }
    /**
     * 清理所有缓存
     */
    public clearCache(): void {
        this.prefabCache.clear();
        this.bundleCache.clear();
    }

    /**
     * 清理prefab缓存
     */
    public clearPrefabCache(): void {
        this.prefabCache.clear();
    }

    /**
     * 清理bundle缓存
     */
    public clearBundleCache(): void {
        this.bundleCache.clear();
    }

    /**
     * 移除指定的prefab缓存
     */
    public removePrefabCache(path: string): void {
        this.prefabCache.delete(path);
    }

    /**
     * 移除指定的bundle缓存
     */
    public removeBundleCache(bundleName: string, isRemote: boolean = false): void {
        const bundleKey = isRemote ? 
            GlobalManager.getRemoteCacheKey(bundleName, true) : 
            bundleName;
        this.bundleCache.delete(bundleKey);
    }

    /**
     * 获取缓存统计信息
     */
    public getCacheInfo(): { prefabCount: number; bundleCount: number; popupCount: number } {
        return {
            prefabCount: this.prefabCache.size,
            bundleCount: this.bundleCache.size,
            popupCount: this.popups.size
        };
    }
}
